package com.qf.flash.ui.chat.db;

import android.content.Context;

import com.hyphenate.EMContactListener;
import com.hyphenate.EMGroupChangeListener;
import com.hyphenate.EMMultiDeviceListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMucSharedFile;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.domain.EaseAvatarOptions;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.model.EaseNotifier;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.qf.dblib.dao.entity.ChatUser;
import com.qf.dblib.dao.entity.InviteMessage;
import com.qf.flash.constant.Constant;
import com.qf.flash.event.ChatEvent;
import com.qf.flash.utils.AppToast;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import static com.qf.flash.constant.Constant.ACTION_CONTACT_CHANAGED;
import static com.qf.flash.constant.Constants.BEAGREED;
import static com.qf.flash.constant.Constants.BEINVITEED;

public class ChatHelper {

    private boolean isGroupAndContactListenerRegisted;
    private static ChatHelper instance = null;
    public synchronized static ChatHelper getInstance() {
        if (instance == null) {
            instance = new ChatHelper();
        }
        return instance;
    }
    public void init(Context context) {
        appContext = context;
        easeUI = EaseUI.getInstance();
        setGlobalListeners();
    }
 
    private void setGlobalListeners() {
        registerGroupAndContactListener();

    }

    public void registerGroupAndContactListener(){
        if(!isGroupAndContactListenerRegisted){
            EMClient.getInstance().groupManager().addGroupChangeListener(new MyGroupChangeListener());
            EMClient.getInstance().contactManager().setContactListener(new MyContactListener());
            EMClient.getInstance().addMultiDeviceListener(new MyMultiDeviceListener());
            isGroupAndContactListenerRegisted = true;
        }

    }

    // 监听添加好友信息
    public class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(String s) {

        }

        @Override
        public void onContactDeleted(String s) {

        }

        @Override
        public void onContactInvited(String username, String reason) {
            // 剔除之前记录，确保无重复消息
            List<InviteMessage> msgs = LitePal.findAll(InviteMessage.class);
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getGroupId() == null && inviteMessage.getFrom().equals(username)) {
                    LitePal.deleteAll(InviteMessage.class,"from = ?", username);
                }
            }

            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            msg.setReason(reason);
            // set invitation status
            msg.setStatus(BEINVITEED);
            notifyNewInviteMessage(msg);
            EventBus.getDefault().post(new ChatEvent(ACTION_CONTACT_CHANAGED));

        }

        @Override
        public void onFriendRequestAccepted(String username) {
            List<InviteMessage> msgs = LitePal.findAll(InviteMessage.class);
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getFrom().equals(username)) {
                    return;
                }
            }
            // save invitation as message
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            AppToast.showToast(username + " accept your to be friend");
            msg.setStatus(BEAGREED);
            notifyNewInviteMessage(msg);
            EventBus.getDefault().post(new ChatEvent(ACTION_CONTACT_CHANAGED));

        }

        @Override
        public void onFriendRequestDeclined(String s) {

        }
    }
    private InviteMessgeDao inviteMessgeDao;
    private Context appContext;
    private EaseUI easeUI;
    public EaseNotifier getNotifier(){
        return easeUI.getNotifier();
    }
    private void notifyNewInviteMessage(InviteMessage msg) {

        if(inviteMessgeDao == null){
            inviteMessgeDao = new InviteMessgeDao(appContext);
        }
        inviteMessgeDao.saveMessage(msg);
        //increase the unread message count
//        inviteMessgeDao.saveUnreadMessageCount(1);
        // notify there is new message
        getNotifier().vibrateAndPlayTone(null);
    }

    public Map<String, EaseUser> getContactList() {
        Map<String, EaseUser> users = new Hashtable<String, EaseUser>();
        List<ChatUser> allChatUser = LitePal.findAll(ChatUser.class);
        for (ChatUser chatUser : allChatUser) {
            String username = chatUser.getUsername();
            EaseUser user = new EaseUser(chatUser.getUsername());
            user.setNickname(chatUser.getNick());
            user.setAvatar(chatUser.getAvatar());
            if (username.equals(Constant.NEW_FRIENDS_USERNAME) || username.equals(Constant.GROUP_USERNAME)
                    || username.equals(Constant.CHAT_ROOM) || username.equals(Constant.CHAT_ROBOT)) {
                user.setInitialLetter("");
            } else {
                EaseCommonUtils.setUserInitialLetter(user);
            }
            users.put(username, user);
        }
        return users;
    }

    // 多设备登陆
    public class MyMultiDeviceListener implements EMMultiDeviceListener {

        @Override
        public void onContactEvent(int i, String s, String s1) {

        }

        @Override
        public void onGroupEvent(int i, String s, List<String> list) {

        }
    }
    /**
     * group change listener
     */
    class MyGroupChangeListener implements EMGroupChangeListener {

        @Override
        public void onInvitationReceived(String s, String s1, String s2, String s3) {

        }

        @Override
        public void onRequestToJoinReceived(String s, String s1, String s2, String s3) {

        }

        @Override
        public void onRequestToJoinAccepted(String s, String s1, String s2) {

        }

        @Override
        public void onRequestToJoinDeclined(String s, String s1, String s2, String s3) {

        }

        @Override
        public void onInvitationAccepted(String s, String s1, String s2) {

        }

        @Override
        public void onInvitationDeclined(String s, String s1, String s2) {

        }

        @Override
        public void onUserRemoved(String s, String s1) {

        }

        @Override
        public void onGroupDestroyed(String s, String s1) {

        }

        @Override
        public void onAutoAcceptInvitationFromGroup(String s, String s1, String s2) {

        }

        @Override
        public void onMuteListAdded(String s, List<String> list, long l) {

        }

        @Override
        public void onMuteListRemoved(String s, List<String> list) {

        }

        @Override
        public void onAdminAdded(String s, String s1) {

        }

        @Override
        public void onAdminRemoved(String s, String s1) {

        }

        @Override
        public void onOwnerChanged(String s, String s1, String s2) {

        }

        @Override
        public void onMemberJoined(String s, String s1) {

        }

        @Override
        public void onMemberExited(String s, String s1) {

        }

        @Override
        public void onAnnouncementChanged(String s, String s1) {

        }

        @Override
        public void onSharedFileAdded(String s, EMMucSharedFile emMucSharedFile) {

        }

        @Override
        public void onSharedFileDeleted(String s, String s1) {

        }
    }
}
